<template>
	<div class="personnelList agentAdd">
		<el-breadcrumb separator="/">
			<el-breadcrumb-item :to="{ path: '/' }">
				<i class="lh lh-caiwu fw_100"></i>
			</el-breadcrumb-item>
			<el-breadcrumb-item>代理商管理</el-breadcrumb-item>
			<el-breadcrumb-item>{{ breadcrumb_name }}</el-breadcrumb-item>
		</el-breadcrumb>
		<div class="content_Box box-shadow">
			<div>
				<h4 class="title border-bottom">{{ breadcrumb_name }}</h4>
				<div class="cont">
					<el-row>
						<el-col :span="24">
							<div class="flex-container">
								<div class="label-name"><i class="lhadmin lhadmin-wujiaoxing"></i>登录账号：</div>
								<div>
									<el-input v-if="!id" v-model="query.username" placeholder="八位以上包含数字、大小写字母"></el-input>
									<span v-else>{{ query.username }}</span>
								</div>
							</div>
						</el-col>
						<el-col :span="24">
							<div class="flex-container">
								<div class="label-name"><i class="lhadmin lhadmin-wujiaoxing" v-if="!id"></i>密码：</div>
								<div>
									<el-input v-model="query.password" placeholder="八位以上包含数字、大小写字母"></el-input>
								</div>
							</div>
						</el-col>
						<el-col :span="24">
							<div class="flex-container">
								<div class="label-name"><i class="lhadmin lhadmin-wujiaoxing"></i>姓名：</div>
								<div>
									<el-input v-model="query.nickname"></el-input>
								</div>
							</div>
						</el-col>
						<el-col :span="24">
							<div class="flex-container">
								<div class="label-name"><i class="lhadmin lhadmin-wujiaoxing"></i>手机号码：</div>
								<div>
									<el-input v-model="query.mobile"></el-input>
								</div>
							</div>
						</el-col>
						<el-col :span="24">
							<div class="flex-container">
								<div class="label-name">性别：</div>
								<div>
									<el-radio v-model="query.sex" label="1">男</el-radio>
									<el-radio v-model="query.sex" label="2">女</el-radio>
								</div>
							</div>
						</el-col>
						<el-col :span="24">
							<div class="flex-container">
								<div class="label-name"><i class="lhadmin lhadmin-wujiaoxing"></i>角色：</div>
								<div>
									<el-select v-model="query.role_id" placeholder="请选择" clearable filterable>
										<el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id"></el-option>
									</el-select>
								</div>
							</div>
						</el-col>
						<el-col :span="24">
							<div class="flex-container">
								<div class="label-name">职务：</div>
								<div>
									<el-input v-model="query.job"></el-input>
								</div>
							</div>
						</el-col>
						<el-col :span="24">
							<div class="flex-container">
								<div class="label-name">Email：</div>
								<div>
									<el-input v-model="query.email"></el-input>
								</div>
							</div>
						</el-col>
					</el-row>
				</div>
				<h4 class="title border-bottom">关联商圈</h4>
				<div class="cont">
					<div v-for="(item, index) in allCities" :key="'only' + index" class="city-checkout">
						<el-checkbox
							class="all-selected"
							:indeterminate="item.isIndeterminate"
							v-model="item.selected"
							@change="handleCheckAllChange(item.selected, index)"
							>{{ item.city_name }}</el-checkbox
						>
						<div class="line"></div>
						<el-checkbox-group v-model="item.checkedCities">
							<el-checkbox
								v-for="(city, sum) in item.data"
								:label="city.id"
								:key="sum"
								@change="handleCheckedCitiesChange(index, sum)"
								>{{ city.area_name }}</el-checkbox
							>
						</el-checkbox-group>
					</div>
				</div>
			</div>
			<div class="footer">
				<el-button round @click="back()">返回</el-button>
				<el-button type="primary" round @click="save()">保存</el-button>
			</div>
		</div>
	</div>
</template>

<script>
var common = require('../../../static/tool.js')
import { PHONE_REGEXP } from '@/utils/util.js'
import {
	fetchCityAreaList,
	agentAddUser,
	agentEditUser,
	fetchAgentList,
	fetchListRole,
	agentUserInfo
} from '@/api/agent.js'
export default {
	name: 'agentAdd',
	data() {
		return {
			manageInfo: JSON.parse(sessionStorage.getItem('manageInfo')), //登录信息
			url: common.url,
			head_url: common.head_url,
			breadcrumb_name: '新增用户',
			id: '',
			query: {
				role_id: '',
				username: '',
				password: '',
				nickname: '',
				sex: '',
				job: '',
				mobile: '',
				email: '',
				type: 2
			},

			allCities: [], //城市列表
			list: [], //人才账单列表
			// agentList: [], //代理商列表
			roleList: [] //角色列表
		}
	},
	created() {},
	mounted() {
		console.log(this.$route.query)
		if (this.$route.query.id) {
			this.id = this.$route.query.id
			this.breadcrumb_name = '编辑用户'
		}
		this.getCityAreaList()
		// this.getAgentList()
		this.getRoleList()
	},
	methods: {
		async getAgentUserInfo() {
			try {
				let res = await agentUserInfo({ id: this.id })
				res.area_id.forEach(it => {
					this.allCities.forEach(city => {
						city.data.forEach(area => {
							if (area.id == it) {
								city.checkedCities.push(it)
							}
						})
						let checkedCount = city.checkedCities.length
						city.selected = checkedCount === city.data.length
						city.isIndeterminate = checkedCount > 0 && checkedCount < city.data.length
					})
				})
				for (let key in this.query) {
					for (let it in res) {
						if (key == it) this.query[key] = res[it]
					}
				}
				this.query.sex = res.sex.toString()
				delete this.query.password
				this.getRoleList()
			} catch (err) {
				console.log(err)
			}
		},
		// 添加/编辑保存
		async save(params = {}) {
			try {
				if (!this.query.username || !this.query.nickname || !this.query.mobile || !this.query.role_id) {
					return this.$message.error('请填写必填项！')
				}
				if (!PHONE_REGEXP.test(this.query.mobile)) {
					return this.$message.error('请填写正确的手机号码')
				}
				let city_id = []
				let area_id = []
				this.allCities.forEach(it => {
					if (it.checkedCities.length > 0) {
						city_id.push(it.city_id)
						area_id = [...area_id, ...it.checkedCities]
					}
				})
				const reqParams = this.computedParams(params)
				if (this.id) {
					await agentEditUser({
						...reqParams,
						city_id: city_id.join(','),
						area_id: area_id.join(','),
						id: this.id
					})
				} else {
					if (!this.query.password) return this.$message.error('请填写必填项！')
					await agentAddUser({
						...reqParams,
						city_id: city_id.join(','),
						area_id: area_id.join(',')
					})
				}
				this.$message.success(`${this.sn ? '修改成功' : '添加成功'}`)
				this.back()
			} catch (err) {
				console.log(err)
			}
		},

		computedParams(params = {}) {
			const { ...rest } = this.query

			return {
				...rest,
				...params
			}
		},

		async getCityAreaList() {
			try {
				let ret = await fetchCityAreaList()
				ret.list.forEach(it => {
					it.selected = false
					it.checkedCities = []
					it.isIndeterminate = false
					it.selected = false
				})
				this.allCities = ret.list
				// 编辑进来调取详情
				if (this.id) this.getAgentUserInfo()
			} catch (err) {
				console.log('err:', err)
			}
		},

		handleCheckAllChange(val, index) {
			const allCities = this.allCities[index]
			if (val) {
				allCities.data.forEach(item => {
					item.selected = true
					allCities.checkedCities.push(item.id)
				})
			} else {
				allCities.checkedCities = []
			}
			allCities.isIndeterminate = false
		},
		handleCheckedCitiesChange(index, sum) {
			const allCities = this.allCities[index]
			allCities.data[sum].selected = !allCities.data[sum].selected

			let checkedCount = allCities.checkedCities.length
			allCities.selected = checkedCount === allCities.data.length
			allCities.isIndeterminate = checkedCount > 0 && checkedCount < allCities.data.length
		},

		// 获取代理商列表
		async getRoleList() {
			try {
				let ret = await fetchListRole({
					agent_id: this.manageInfo.user_info.agent_id,
					type: 2, //代理商角色
					page: 1,
					limit: 10000
				})
				this.roleList = ret.list.map(it => {
					return {
						id: it.id,
						name: it.name
					}
				})
			} catch (err) {
				console.log('err:', err)
			}
		},

		//重置
		async resetBtn() {
			this.resetData()
			this.getList()
		},
		//重置请求数据
		resetData() {
			this.pageNum = 1
			for (let key in this.query) {
				this.query[key] = ''
			}
			this.query.city_id = this.allCities[0].id
		},

		shearchBtn() {
			console.log(this.query)
			// 搜索
			this.pageNum = 1
			this.getList()
		},

		back() {
			this.$router.go(-1)
		}
	},
	filters: {}
}
</script>

<style scoped>
.flex-container {
	display: flex;
	line-height: 40px;
}
.content_Box {
	padding: 10px;
}
.content_Box .title {
	padding-bottom: 10px;
}
.content_Box .cont {
	padding: 20px 0;
	font-size: 14px;
}
.content_Box .label-name {
	width: 120px;
	text-align: right;
	color: #666666;
}
.agentAdd .line {
	height: 5px;
}
.city-checkout {
	border-bottom: 1px dashed #ebebeb;
	padding: 10px 0;
}
.city-checkout:last-child {
	border-bottom: none;
}
.all-selected {
	color: #222222;
}
.footer {
	padding: 50px 0 50px 200px;
}
.footer button {
	width: 100px;
	margin-left: 40px;
}
</style>
<style>
.agentAdd .el-input__inner,
.agentAdd .el-textarea__inner {
	width: 300px;
}
.agentAdd .el-checkbox-group .el-checkbox {
	min-width: 120px;
	margin-bottom: 5px;
}
</style>



// WEBPACK FOOTER //
// src/components/agent/AdminAdd.vue